/**
 * 模型对比视图组件
 * 支持2-4个模型的并排展示和差异高亮
 */

import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Row, Col, Card, Tag, Spin, Empty, Tooltip, Badge } from 'antd';
import { 
  RobotOutlined, 
  ClockCircleOutlined, 
  ThunderboltOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons';
import { diffWords } from 'diff';
import './ComparisonView.css';

export interface ModelResult {
  model: string;
  content: string;
  tokens: number;
  time: number;
  status: 'pending' | 'generating' | 'completed' | 'failed' | 'timeout';
  error?: string;
}

interface ComparisonViewProps {
  results: ModelResult[];
  onModelSelect?: (model: string) => void;
  selectedModel?: string;
  showDiff?: boolean;
  syncScroll?: boolean;
  loading?: boolean;
}

const ComparisonView: React.FC<ComparisonViewProps> = ({
  results,
  onModelSelect,
  selectedModel,
  showDiff = true,
  syncScroll = true,
  loading = false
}) => {
  const [columnWidth, setColumnWidth] = useState<number>(24 / Math.max(results.length, 1));
  const scrollRefs = useRef<(HTMLDivElement | null)[]>([]);
  const [isScrolling, setIsScrolling] = useState(false);

  // 动态计算列宽
  useEffect(() => {
    const width = results.length > 0 ? Math.floor(24 / results.length) : 24;
    setColumnWidth(width);
  }, [results.length]);

  // 同步滚动处理
  const handleScroll = (index: number) => {
    if (!syncScroll || isScrolling) return;
    
    setIsScrolling(true);
    const scrollTop = scrollRefs.current[index]?.scrollTop || 0;
    
    scrollRefs.current.forEach((ref, i) => {
      if (ref && i !== index) {
        ref.scrollTop = scrollTop;
      }
    });
    
    setTimeout(() => setIsScrolling(false), 50);
  };

  // 计算与第一个结果的差异
  const getDiffHighlight = useMemo(() => {
    if (!showDiff || results.length < 2) return {};
    
    const baseContent = results[0]?.content || '';
    const diffs: { [key: string]: any[] } = {};
    
    results.slice(1).forEach((result, index) => {
      const diff = diffWords(baseContent, result.content);
      diffs[result.model] = diff;
    });
    
    return diffs;
  }, [results, showDiff]);

  // 渲染差异高亮文本
  const renderDiffContent = (model: string, content: string, index: number) => {
    if (!showDiff || index === 0 || !getDiffHighlight[model]) {
      return <div className="content-text">{content}</div>;
    }

    const diff = getDiffHighlight[model];
    return (
      <div className="content-text diff-content">
        {diff.map((part: any, i: number) => {
          if (part.added) {
            return <span key={i} className="diff-added">{part.value}</span>;
          }
          if (part.removed) {
            return null; // 不显示删除的部分
          }
          return <span key={i}>{part.value}</span>;
        })}
      </div>
    );
  };

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'generating':
        return <LoadingOutlined style={{ color: '#1890ff' }} />;
      case 'failed':
      case 'timeout':
        return <CloseCircleOutlined style={{ color: '#f5222d' }} />;
      default:
        return <ClockCircleOutlined style={{ color: '#8c8c8c' }} />;
    }
  };

  // 获取模型标签颜色
  const getModelTagColor = (model: string) => {
    const colors: { [key: string]: string } = {
      'gpt-4': 'purple',
      'gpt-3.5-turbo': 'blue',
      'qwen-max': 'cyan',
      'ernie-bot-4': 'green',
      'glm-4': 'orange'
    };
    return colors[model] || 'default';
  };

  if (loading && results.length === 0) {
    return (
      <div className="comparison-loading">
        <Spin size="large" tip="正在生成对比结果..." />
      </div>
    );
  }

  if (results.length === 0) {
    return (
      <Empty 
        description="暂无对比结果"
        image={Empty.PRESENTED_IMAGE_SIMPLE}
      />
    );
  }

  return (
    <div className="comparison-view">
      <Row gutter={[16, 16]}>
        {results.map((result, index) => (
          <Col 
            key={result.model} 
            xs={24} 
            sm={24} 
            md={results.length > 2 ? 12 : columnWidth}
            lg={columnWidth}
          >
            <Card
              className={`comparison-card ${selectedModel === result.model ? 'selected' : ''}`}
              hoverable={result.status === 'completed'}
              onClick={() => result.status === 'completed' && onModelSelect?.(result.model)}
              title={
                <div className="card-header">
                  <div className="model-info">
                    <RobotOutlined className="model-icon" />
                    <Tag color={getModelTagColor(result.model)}>
                      {result.model}
                    </Tag>
                    {selectedModel === result.model && (
                      <Badge status="success" text="已选择" />
                    )}
                  </div>
                  <div className="status-info">
                    {getStatusIcon(result.status)}
                    <span className="status-text">{result.status}</span>
                  </div>
                </div>
              }
              extra={
                result.status === 'completed' && (
                  <div className="metrics">
                    <Tooltip title="生成时间">
                      <span className="metric">
                        <ClockCircleOutlined />
                        {result.time.toFixed(1)}s
                      </span>
                    </Tooltip>
                    <Tooltip title="Token使用量">
                      <span className="metric">
                        <ThunderboltOutlined />
                        {result.tokens}
                      </span>
                    </Tooltip>
                  </div>
                )
              }
            >
              <div 
                className="card-content"
                ref={el => scrollRefs.current[index] = el}
                onScroll={() => handleScroll(index)}
              >
                {result.status === 'completed' ? (
                  renderDiffContent(result.model, result.content, index)
                ) : result.status === 'generating' ? (
                  <div className="generating">
                    <Spin tip="生成中..." />
                  </div>
                ) : result.status === 'failed' || result.status === 'timeout' ? (
                  <div className="error-content">
                    <CloseCircleOutlined />
                    <p>{result.error || '生成失败'}</p>
                  </div>
                ) : (
                  <div className="pending">
                    <ClockCircleOutlined />
                    <p>等待生成...</p>
                  </div>
                )}
              </div>
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
};

export default ComparisonView;